package com.example;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/setsession")
public class SetSession extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // session 服务器会给每个浏览器(客户端)分配一个session
        // 服务器会在cookie里写入一个sessionID, 再后面的连接中读取这个ID去服务器内部匹配对应的session
        HttpSession session = req.getSession();
        
        Cookie[] cookies = req.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie ck = cookies[i];
            if(ck.getName().equals("JSESSIONID")){
                ck.setMaxAge(24*60*60);
            }
        }

        session.setAttribute("number", 100);
        String sessionId = session.getId();

        if(session.isNew()){
            resp.getWriter().write("session 创建成功, ID为" + sessionId);
        }else{
            resp.getWriter().write("session 已存在, ID为" + sessionId);
        }


    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
